package com.et.u1.vm.home;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.MediaController;

import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.et.u1.R;
import com.et.u1.databinding.FragmentHomeBinding;
import com.et.u1.uitl.DataKt;
import com.et.u1.vm.base.BaseFragment;
import com.et.u1.vm.shop.ShopFragment;
import com.et.util.ShellKt;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.loader.ImageLoader;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomeViewModel> {

    private Timer timer;
    private int bubbleRefreshTime = 0;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @NotNull
    @Override
    public FragmentHomeBinding provideViewBinding(@NotNull LayoutInflater inflater, @org.jetbrains.annotations.Nullable ViewGroup container, @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        return FragmentHomeBinding.inflate(inflater, container, false);
    }

    @NotNull
    @Override
    public HomeViewModel provideViewModel() {
        return new ViewModelProvider(this).get(HomeViewModel.class);
    }

    @Override
    public void initEvent() {
        initVideoView();
        initBubble();
        binding.bubble.setOnClickListener(v -> replaceFragment(ShopFragment.newInstance()));
    }

    @Override
    public void onResume() {
        super.onResume();
        showHome(false);

    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        bubbleRefreshTime = binding.bubble.getBubbleRefreshTime();
    }

    private void initBubble() {
        binding.bubble.initParams(DataKt.getSize().x, DataKt.getSize().y);

        if (bubbleRefreshTime == 0 || bubbleRefreshTime > 70) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    StringBuilder string = new StringBuilder(1024);
                    ShellKt.shell("top -m 1 -n 1", string, true);
                    String s = string.toString();
                    String[] split = s.split("[%\\u0020]");
                    Log.d("CPU", split[1]);
                    if (Integer.parseInt(split[1]) >= 60) {
                        binding.bubble.setBubbleRefreshTime(binding.bubble.getBubbleRefreshTime() + 10);
                    } else {
                        if (binding.bubble.getBubbleRefreshTime() > 20) {
                            binding.bubble.setBubbleRefreshTime(binding.bubble.getBubbleRefreshTime() - 10);
                        }
                    }
                    Log.d("CPU======", String.valueOf(binding.bubble.getBubbleRefreshTime()));
                }
            }, 0, 3000);
        } else {
            binding.bubble.setBubbleRefreshTime(bubbleRefreshTime);
        }
    }

    private void initVideoView() {
        ContentResolver contentResolver = Objects.requireNonNull(getContext()).getContentResolver();
        String[] projection = new String[]{MediaStore.Video.Media.DISPLAY_NAME};
        Cursor cursor = contentResolver.query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
        cursor.moveToFirst();
        String videoUrl = null;
        for (int counter = 0; counter < cursor.getCount(); counter++) {
            videoUrl = Environment.getExternalStorageDirectory().getPath() + "/" + cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
            cursor.moveToNext();
        }
        cursor.close();
        if (videoUrl != null) {
            //设置视频控制器
            MediaController controller = new MediaController(getContext());

            controller.hide();

            assert binding.videoView != null;
            binding.videoView.setMediaController(controller);
            //播放完成回调
            binding.videoView.setOnCompletionListener(mp -> binding.videoView.start());
            //设置视频路径
            binding.videoView.setVideoPath(videoUrl);
            //开始播放视频
            binding.videoView.start();
        } else {
            assert binding.videoView != null;
            binding.videoView.setVisibility(View.GONE);
            initBanner();
        }
    }


    private void initBanner() {
        Banner mBanner = binding.mBanner;
        int[] imageResourceID = new int[]{R.mipmap.index, R.mipmap.index, R.mipmap.index, R.mipmap.index};
        List<Integer> imgeList = new ArrayList<>();

        for (int j : imageResourceID) {
            imgeList.add(j);
            assert mBanner != null;
            mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(context).load(path).into(imageView);
                }
            });
            mBanner.setBannerAnimation(Transformer.RotateDown);
            mBanner.setImages(imgeList);
            mBanner.setBannerStyle(BannerConfig.NOT_INDICATOR);
            mBanner.setDelayTime(3_000);
            mBanner.setOnBannerListener(position -> {
            });
            mBanner.start();
        }
    }


}